package com.leo.base.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @ClassName FileUtil
 * @Description 文件操作手册
 * @Author wangss
 * @date 2020.10.16 15:39
 * @Version 1.0
 */
@Slf4j
@Component
public class FileUtil {

    @Value("${file.cache.path}")
    private String path;

    /**
     * 对多个文件进行缓存
     *
     * @param files
     * @return
     */
    public File[] cacheFiles(MultipartFile[] files) {
        if (ArrayUtils.isEmpty(files)) {
            return null;
        }
        // 如果失败直接返回null
        int length = files.length;
        File[] newFils = new File[length];
        for (int i = 0; i < length; i++) {
            File file = cacheFile(files[i]);
            if (Objects.isNull(file)) {
                return null;
            }
            newFils[i] = file;
        }
        return newFils;
    }

    /**
     * 单个文件进行缓存
     *
     * @param file
     * @return
     */
    public File cacheFile(MultipartFile file) {
        // 获取文件名称
        String fileName = file.getOriginalFilename();
        // 将文件名加上时间戳
        fileName = FileUtil.getFileName(fileName);

        // 判断上传路径是否存在
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }

        // 保存文件
        if (!file.isEmpty()) {
            File newFile = new File(path + File.separator + fileName);
            try (FileOutputStream fos = new FileOutputStream(newFile);
                 BufferedOutputStream bos = new BufferedOutputStream(fos)) {
                bos.write(file.getBytes());
                bos.flush();
                log.info("File [{}] save success", fileName);
                return newFile;
            } catch (Exception e) {
                log.error("File [{}] save fail, cause [{}]", fileName, e.getMessage());
            }
        }
        return null;
    }

    private static String getFileName(String fileName) {
        // 设置时间格式
        final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        // 当前时间
        String nowTimeStr = sDateFormate.format(new Date());
        // 如果存在后缀，则进行处理
        int index = fileName.indexOf(46);
        if (index > -1) {
            fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);
        } else {
            fileName = fileName + "_" + nowTimeStr;
        }
        return fileName;
    }

}
